package com.zoe.onelink.business.util;

import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.common.exception.ApiException;
import com.zoe.onelink.util.IdUtil;
import com.zoe.onelink.util.ValidUtil;
import lombok.Data;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>标题: 使用FTP处理文件(上传，下载，删除)工具类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2016</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: zhx
 * @date
 */
@Data
public class FtpFileUtil {
    /**
     * 本地字符编码
     */
    private static final String LOCAL_CHARSET = "GBK";

    private static final String UTF8_CHARSET = "UTF-8";

    /**
     * FTP协议里面，规定文件名编码为iso-8859-1
     */
    private static final String SERVER_CHARSET = "ISO-8859-1";

    private static String CHARSET = UTF8_CHARSET;

    private static FtpFileUtil self;

    @Autowired(required = false)
    private Prop prop = new Prop();


    @Data
    @ConfigurationProperties(prefix = "global.ftp.default")
    public static class Prop {
        private String host;
        private Integer port;
        private String username;
        private String password;
        private String serverUrl;
        private List<String> fileExtensions;
    }

    @PostConstruct
    public void inject() {
        self = this;
    }

    public static String getServerUrl() {
        return self.getProp().getServerUrl();
    }

    public static String getHost() {
        return self.getProp().getHost();
    }

    public static int getPort() {
        return self.getProp().getPort();
    }

    public static String getUserName() {
        return self.getProp().getUsername();
    }

    public static String getPassword() {
        return self.getProp().getPassword();
    }

    /**
     * ftp连接
     *
     * @param host     地址
     * @param port     端口号
     * @param userName 用户名
     * @param password 密码
     * @return
     * @throws Exception
     */
    public static FTPClient connect(String host, int port, String userName, String password) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.setRemoteVerificationEnabled(false);
            int reply;
            ftpClient.connect(host, port);
            ftpClient.login(userName, password);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就使用本地编码（GBK）.
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                CHARSET = UTF8_CHARSET;
                ftpClient.setControlEncoding(CHARSET);
            } else {
                CHARSET = LOCAL_CHARSET;
                ftpClient.setControlEncoding(CHARSET);
            }
            //被动模式,需要服务端开启一段端口用来传输
            ftpClient.enterLocalPassiveMode();

            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        }
        return ftpClient;
    }

    /**
     * ftp连接
     *
     * @param host     地址
     * @param port     端口号
     * @param userName 用户名
     * @param password 密码
     * @return
     * @throws Exception
     */
    public static FTPClient connectStream(String host, int port, String userName, String password) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            int reply;
            ftpClient.connect(host, port);

            if (ftpClient.login(userName, password)) {
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                // 开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就使用本地编码（GBK）.
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                    CHARSET = UTF8_CHARSET;
                    ftpClient.setControlEncoding(CHARSET);
                } else {
                    CHARSET = LOCAL_CHARSET;
                    ftpClient.setControlEncoding(CHARSET);
                }
                //被动模式,需要服务端开启一段端口用来传输
                ftpClient.enterLocalPassiveMode();
            } else {
                throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, "ftp连接失败", "ftp连接失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        }
        return ftpClient;
    }

    /**
     * 文件上传
     * 文件名使用uuid
     *
     * @param file       文件
     * @param folderName 文件夹名称
     */
    public static String uploadFile(MultipartFile file, String fileNamePre, String folderName) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String extRemoveSpot = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
        String fileName = (ValidUtil.isEmptyOrNull(fileNamePre) ? IdUtil.uuid() : fileNamePre) + "." + extRemoveSpot;
        uploadFile(file.getInputStream(), fileName, folderName);
        return fileName;
    }

    /**
     * 文件上传
     */
    public static void uploadBatchFile(List<String> reportFileNameList, String localFolder, String folderName) throws Exception {
        for (String reportFileName : reportFileNameList) {
            boolean isMatch = false;
            for (String fileExtendName : self.getProp().getFileExtensions()) {
                if (reportFileName.toLowerCase().endsWith(fileExtendName.toLowerCase())) {
                    isMatch = true;
                    continue;
                }
            }
            if (!isMatch) {
                throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, "不允许上传该后缀文件", "不允许上传该后缀文件");
            }
        }

        // 上传文件
        FTPClient ftpClient = connectStream(getHost(), getPort(), getUserName(), getPassword());
        try {
            ftpClient.makeDirectory(folderName);
            if (ftpClient.changeWorkingDirectory(folderName)) {
                for (String reportFileName : reportFileNameList) {
                    File file = new File(localFolder + reportFileName);
                    if (file.exists()) {
                        InputStream is = new FileInputStream(file);
                        //上传文件
                        //FTP协议规定文件编码格式为ISO-8859-1
                        reportFileName = new String(reportFileName.getBytes(CHARSET), SERVER_CHARSET);
                        OutputStream out = ftpClient.storeFileStream(reportFileName);
                        byte[] byteArray = new byte[4096];
                        int read = 0;
                        while ((read = is.read(byteArray)) != -1) {
                            out.write(byteArray, 0, read);
                        }
                        out.close();
                        is.close();
                        ftpClient.completePendingCommand();
                    }
                }
                //返回到跟目录
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 文件上传
     *
     * @param in         上传的文件流
     * @param fileName   文件名称
     * @param folderName 文件夹名称
     */
    public static void uploadFile(InputStream in, String fileName, String folderName) throws Exception {
        FTPClient ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
        try {
            boolean isMatch = false;
            for (String fileExtendName : self.getProp().getFileExtensions()) {
                if (fileName.toLowerCase().endsWith(fileExtendName.toLowerCase())) {
                    ftpClient.makeDirectory(folderName);
                    if (ftpClient.changeWorkingDirectory(folderName)) {
                        fileName = new String(fileName.getBytes(CHARSET), SERVER_CHARSET);
                        ftpClient.storeFile(fileName, in);
                        //返回到跟目录
                        ftpClient.changeWorkingDirectory("/");
                    }
                    isMatch = true;
                    break;
                }
            }
            if (!isMatch) {
                throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, "不允许上传该后缀文件", "不允许上传该后缀文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 上传文件夹
     *
     * @param remoteFolder    远程目录
     * @param localFolderName 本地文件夹目录
     * @throws Exception
     */
    public static void uploadFolder(String remoteFolder, String localFolderName) throws Exception {
        File folderFile = new File(localFolderName);
        if (!folderFile.exists()) {
            return;
        }
        File[] fileList = folderFile.listFiles();
        if (fileList.length == 0) {
            return;
        }
        FTPClient ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
        try {
            ftpClient.makeDirectory(remoteFolder);
            if (ftpClient.changeWorkingDirectory(remoteFolder)) {
                for (int i = 0; i < fileList.length; i++) {
                    File file = fileList[i];
                    if (file.exists()) {
                        for (String fileExtendName : self.getProp().getFileExtensions()) {
                            if (file.getName().toLowerCase().endsWith(fileExtendName.toLowerCase())) {
                                String fileName = new String(file.getName().getBytes(CHARSET), SERVER_CHARSET);
                                ftpClient.storeFile(fileName, new FileInputStream(file));
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    public static void uploadBatchFolder(String remoteFolder, String localFolderName) throws Exception {
        File folderFile = new File(localFolderName);
        if (!folderFile.exists()) {
            return;
        }
        File[] fileList = folderFile.listFiles();
        if (fileList.length == 0) {
            return;
        }
        FTPClient ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
        try {
            ftpClient.makeDirectory(remoteFolder);
            if (ftpClient.changeWorkingDirectory(remoteFolder)) {
                for (int i = 0; i < fileList.length; i++) {
                    File file = fileList[i];
                    commonUpload(fileList[i], ftpClient, self.getProp().getFileExtensions().toArray(new String[0]));
                    File[] subFiles = file.listFiles();
                    for (int j = 0; j < subFiles.length; j++) {
                        commonUpload(subFiles[j], ftpClient, self.getProp().getFileExtensions().toArray(new String[0]));
                    }
                    ftpClient.changeToParentDirectory();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    public static void commonUpload(File file, FTPClient ftpClient, String[] fileExtendNames) throws Exception {

        if (file.exists()) {
            if (file.isDirectory()) {
                ftpClient.makeDirectory(file.getName());
                ftpClient.changeWorkingDirectory(file.getName());
                return;
            }
            if (file.isFile()) {
                for (String fileExtendName : fileExtendNames) {
                    if (file.getName().toLowerCase().endsWith(fileExtendName.toLowerCase())) {
                        String fileName = new String(file.getName().getBytes(CHARSET), SERVER_CHARSET);
                        ftpClient.storeFile(fileName, new FileInputStream(file));
                    }
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param folderName 文件夹名称
     * @param fileName   文件名称
     */
    public static void deleteFile(String folderName, String fileName) throws IOException {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderName)) {
                ftpClient.dele(new String(fileName.getBytes(CHARSET), SERVER_CHARSET));
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 批量删除文件
     *
     * @param folderName 文件夹名称
     * @param fileList   文件列表
     */
    public static void deleteFileList(String folderName, List<String> fileList) throws IOException {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderName)) {
                for (String fileName : fileList) {
                    ftpClient.dele(new String(fileName.getBytes(CHARSET), SERVER_CHARSET));
                }
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 批量删除文件,排除列表
     *
     * @param folderName      文件夹名称
     * @param excludeFileList 文件列表
     */
    public static void deleteFileExcludeList(String folderName, List<String> excludeFileList) throws IOException {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderName)) {
                FTPFile[] ftpFiles = ftpClient.listFiles();
                if (ftpFiles != null && ftpFiles.length > 0) {
                    for (FTPFile file : ftpFiles) {
                        if (!excludeFileList.contains(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET))) {
                            ftpClient.deleteFile(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET));
                        }
                    }
                }
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 删除文件夹
     *
     * @param folderPath
     * @throws Exception
     */
    public static void deleteFolder(String folderPath) throws Exception {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderPath)) {
                FTPFile[] ftpFiles = ftpClient.listFiles();
                if (ftpFiles != null && ftpFiles.length > 0) {
                    for (FTPFile file : ftpFiles) {
                        ftpClient.deleteFile(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET));
                    }
                }
                if (ftpClient.changeWorkingDirectory("/")) {
                    ftpClient.removeDirectory(folderPath);
                    ftpClient.changeToParentDirectory();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 批量删除文件夹
     *
     * @param folderPathList 文件夹列表
     * @throws Exception
     */
    public static void deleteBatchFolder(List<String> folderPathList) throws Exception {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            for (String folderPath : folderPathList) {
                //切换FTP目录
                if (ftpClient.changeWorkingDirectory(folderPath)) {
                    FTPFile[] ftpFiles = ftpClient.listFiles();
                    if (ftpFiles != null && ftpFiles.length > 0) {
                        for (FTPFile file : ftpFiles) {
                            ftpClient.deleteFile(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET));
                        }
                    }
                    if (ftpClient.changeWorkingDirectory("/")) {
                        ftpClient.removeDirectory(folderPath);
                        ftpClient.changeToParentDirectory();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 重命名文件
     *
     * @param folderName 文件夹名称
     * @param oldName    旧文件名
     * @param newName    新文件名
     */
    public static void reName(String folderName, String oldName, String newName) throws IOException {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderName)) {
                ftpClient.rename(oldName, newName);
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 下载文件
     *
     * @param folderName 文件夹名称
     * @param localPath  文件下载的本地地址
     */
    public static void downloadFile(String folderName, String localPath) throws IOException {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderName)) {
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile file : ftpFiles) {
                    File localFile = new File(localPath + "/" + file.getName());
                    OutputStream os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET), os);
                    os.close();
                }
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 下载文件
     *
     * @param folderName 文件夹名称
     * @param fileName   文件名
     * @param localPath  文件下载的本地地址
     */
    public static void downloadFile(String folderName, String fileName, String localPath) throws IOException {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderName)) {
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile file : ftpFiles) {
                    if (fileName.equalsIgnoreCase(file.getName())) {
                        File localFile = new File(localPath + "/" + file.getName());
                        OutputStream os = new FileOutputStream(localFile);
                        ftpClient.retrieveFile(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET), os);
                        os.close();
                    }
                }
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 下载文件
     *
     * @param folderName 文件夹名称
     * @param fileName   文件名
     * @param localPath  文件下载的本地地址
     */
    public static void downloadFile(String folderName, String fileName, String localPath, String localFileName) throws IOException {
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderName)) {
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile file : ftpFiles) {
                    if (fileName.equalsIgnoreCase(file.getName())) {
                        File localFile = new File(localPath + "/" + localFileName);
                        OutputStream os = new FileOutputStream(localFile);
                        ftpClient.retrieveFile(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET), os);
                        os.close();
                    }
                }
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 复制文件
     *
     * @param sourceFileName 源文件名称
     * @param sourceDir      源文件目录
     * @param targetFileName 目标文件名称
     * @param targetDir      目标文件目录
     * @throws IOException
     */
    public static void copyFile(String sourceFileName, String sourceDir, String targetFileName, String targetDir)
            throws IOException {
        if (ValidUtil.isEmptyOrNull(sourceFileName)) {
            return;
        }
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            ftpClient.enterLocalPassiveMode();
            ftpClient.makeDirectory(targetDir);
            // 变更工作路径
            if (!ftpClient.changeWorkingDirectory(sourceDir)) {
                return;
            }
            // 设置以二进制流的方式传输
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ByteArrayOutputStream fos = new ByteArrayOutputStream();
            ftpClient.retrieveFile(new String(sourceFileName.getBytes(CHARSET), SERVER_CHARSET), fos);
            // 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
            InputStream is = new ByteArrayInputStream(fos.toByteArray());
            if (is != null) {
                ftpClient.changeWorkingDirectory("/");
                // 变更工作路径
                if (ftpClient.changeWorkingDirectory(targetDir)) {
                    ftpClient.storeFile(new String(targetFileName.getBytes(CHARSET), SERVER_CHARSET), is);
                    is.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String folderName = "/report/test";
        List<String> excludeFileList = new ArrayList<>(1);
        excludeFileList.add("范德萨_arg.rpx");
        FTPClient ftpClient = null;
        try {
            ftpClient = connect("192.168.2.226", 21, "zoeftp", "zysoft");
            //切换FTP目录
            if (ftpClient.changeWorkingDirectory(folderName)) {
                FTPFile[] ftpFiles = ftpClient.listFiles();
                if (ftpFiles != null && ftpFiles.length > 0) {
                    for (FTPFile file : ftpFiles) {
                        if (!excludeFileList.contains(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET))) {
                            ftpClient.deleteFile(new String(file.getName().getBytes(CHARSET), SERVER_CHARSET));
                        }
                    }
                }
                ftpClient.changeWorkingDirectory("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw ApiException.createEx(ExceptionCodeEnum.BIZ_ERROR, e.getMessage(), e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 复制文件
     *
     * @param sourceDir 源文件目录
     * @param targetDir 目标文件目录
     * @throws IOException
     */
    public static void copyFile(String sourceDir, String targetDir) throws IOException {
        FTPClient ftpClient = null;
        try {
            // 删除目标文件目录
            deleteFolder(targetDir);

            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            ftpClient.makeDirectory(targetDir);
            // 变更工作路径
            ftpClient.enterLocalPassiveMode();
            if (ftpClient.changeWorkingDirectory(sourceDir)) {
                FTPFile[] ftpSourceFiles = ftpClient.listFiles();
                if (ftpSourceFiles.length == 0) {
                    return;
                }
                List<Map<String, Object>> fosList = new ArrayList<>(ftpSourceFiles.length);
                for (FTPFile ftpFile : ftpSourceFiles) {
                    // 设置以二进制流的方式传输
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                    ByteArrayOutputStream fos = new ByteArrayOutputStream();
                    String fileName = new String(ftpFile.getName().getBytes(CHARSET), SERVER_CHARSET);
                    ftpClient.retrieveFile(fileName, fos);
                    // 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
                    InputStream is = new ByteArrayInputStream(fos.toByteArray());

                    Map<String, Object> map = new HashMap<>();
                    map.put("fileName", fileName);
                    map.put("is", is);
                    fosList.add(map);
                }

                ftpClient.changeWorkingDirectory("/");
                if (ftpClient.changeWorkingDirectory(targetDir)) {
                    for (Map<String, Object> map : fosList) {
                        if (null != map.get("is") && null != map.get("fileName")) {
                            InputStream is = (InputStream) map.get("is");
                            if (is != null) {
                                ftpClient.storeFile(map.get("fileName").toString(), is);
                                is.close();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            throw ApiException.createEx(e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
    }

    /**
     * 获取文件流
     *
     * @param fileName 文件名称
     * @param dir      文件目录
     */
    public static InputStream getFileInputStream(String fileName, String dir) throws Exception {
        InputStream io = null;
        FTPClient ftpClient = null;
        try {
            ftpClient = connect(getHost(), getPort(), getUserName(), getPassword());
            // 变更工作路径
            ftpClient.enterLocalPassiveMode();
            if (ftpClient.changeWorkingDirectory(dir)) {
                io = ftpClient.retrieveFileStream(fileName);
            }
        } catch (Exception e) {
            throw ApiException.createEx(e.getMessage());
        } finally {
            if (null != ftpClient) {
                ftpClient.logout();
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
        return io;
    }
}
